package com.aabte.lota.auth.auth.shiro;

import com.aabte.commons.rest.exception.ApiException;
import com.aabte.lota.auth.auth.bean.constant.LoginConstants;
import com.aabte.lota.auth.auth.bean.enums.LoginApiErrorCode;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/5
 */
@Slf4j
public class JwtAuthenticationFilter implements Filter {

  public static final String HEADER_NAME_TOKEN = LoginConstants.HEADER_NAME_AUTHORIZATION;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpServletRequest = WebUtils.toHttp(request);

    String token = httpServletRequest.getHeader(HEADER_NAME_TOKEN);
    if (StringUtils.isNotBlank(token)) {
      JwtToken jwtToken = new JwtToken(token);
      Subject subject = SecurityUtils.getSubject();
      try {
        subject.login(jwtToken);
      } catch (AuthenticationException e) {
        throw new ApiException(
            LoginApiErrorCode.AUTHENTICATION_REQUIRED.getStatus(),
            LoginApiErrorCode.AUTHENTICATION_REQUIRED.getCode(),
            e.getMessage());
      }
      // 放行，由ModularRealmAuthorizer来做鉴权
      chain.doFilter(request, response);
      return;
    }
    throw new ApiException(LoginApiErrorCode.TOKEN_IS_BLANK);
  }
}
